package pers.zw.study.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "FilterCharacterEncoding", urlPatterns = "/*")
public class FilterCharacterEncoding implements Filter {

    private FilterConfig filterConfig = null;

    private final String defaultCharset = "UTF-8";

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String charset = filterConfig.getInitParameter("charset");
        if (charset == null) {
            charset = defaultCharset;
        }
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);
        response.setContentType("text/html;charset=" + charset);

        MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request);
        chain.doFilter(requestWrapper, response);
    }

    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }
}

class MyCharacterEncodingRequest extends HttpServletRequestWrapper {

    private HttpServletRequest request;

    public MyCharacterEncodingRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name) {
        try {
            String value = this.request.getParameter(name);
            if (value == null) return null;
            if (this.request.getMethod().equalsIgnoreCase("get")) {
                value = new String(value.getBytes("ISO8859-1"), this.request.getCharacterEncoding());
            }
            return value;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}